const express = require('express');
const path = require('path');
const router = express.Router();
const multer = require('multer');
const UUID = require('uuid');
const fs = require('fs');
const xlsx = require('node-xlsx');
const mailer = require('../../service/sendMail');

const storage = multer.diskStorage({
    destination: path.resolve(__dirname, '../upload'),
    filename: function (req, file, cb) {
        let extName = file.originalname.slice(file.originalname.lastIndexOf('.'));
        let fileName = UUID.v1();
        cb(null, fileName + extName)
    }
});

const imageUploader = multer({
    storage: storage
}).array('email', 12);


router.post('/importEmail', imageUploader, function (req, res, next) {
    let emailUrl = req.files[0].path;
    let type = req.query.type;
    let sheets = xlsx.parse(emailUrl);
    let arr = [];
    sheets.forEach(function (sheet) {
        if (sheet && sheet['data'] && sheet['data'].length > 0) {
            for (let rowId in sheet['data']) {
                if (rowId) {
                    let row = sheet['data'][rowId];
                    if (row && row.length > 0) {
                        row.forEach(k => {
                            if (k) {
                                k=k.toString();
                                k = k.trim();
                                let d = [];
                                if (type && type === 'f') {
                                    if (k && k.indexOf('----') > -1) {
                                        let f = k.substring(0, k.indexOf('----')).trim();
                                        let p = k.substring(k.indexOf('----') + 4).trim();
                                        if (f && p) {
                                            d.push(f);
                                            d.push(p);
                                            arr.push(d);
                                        }
                                    }
                                } else if (type && type === 't') {
                                    if (k&&verifyMail(k)) {
                                        arr.push(k);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
    });
    fs.unlinkSync(emailUrl);
    res.json({data: arr});
});
module.exports = router;
function verifyMail(str) {
    let reg=/^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
    return reg.test(str);
}
